package com.hao.mydownloadlist.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;


import com.hao.mydownloadlist.MainActivity;
import com.hao.mydownloadlist.event.DownloadEvent;
import com.hao.mydownloadlist.event.DownloadStateEvent;
import com.hao.mydownloadlist.notification.NotificationUtils;
import com.hao.mydownloadlist.service.utils.DownloadList;
import com.hao.mydownloadlist.service.utils.DownloadPath;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class VersionUpdateService extends Service {

    private static final String TAG = VersionUpdateService.class.getSimpleName();


//    public static final String APP_NAME = "APP_NAME";
//    public static final String URL = "URL";
//    public static final String ICON_ID = "ICON_ID";
//    public static final String MAIN_ACTIVITY_REFERENCE = "MAIN_ACTIVITY_REFERENCE";
//    public static final String APK_CACHE_PATH = "APK_CACHE_PATH";


    private static final int DOWN_OK = 1; // 下载完成
    private static final int DOWN_ERROR = 0;


//    private NotificationManager notificationManager;
//    private Notification notification;


//    private Intent updateIntent;
//    private PendingIntent pendingIntent;
    private String updateFile;

//    private int notification_id = 0;
    private static Class<?> mCls;


    //路径处理帮助类
    private DownloadPath downloadPath;
    //是否已经进入下载状态
    public static boolean isDownloadState = false;
    //下载中的索引
    private int mPosition;

    //是否已经开启服务
    private static boolean isStartServers = false;


    /***
     * 更新UI
     */
    final Handler handler = new Handler() {
        @SuppressWarnings("deprecation")
        @Override
        public void handleMessage(Message msg) {
            String nameMp = (String) msg.obj;
            int iconIdMp = msg.arg1;
            NotificationUtils notificationUtils = NotificationUtils.getNotificationUtilsList().get(mPosition - 1);
            switch (msg.what) {
                case DOWN_OK:
                    notificationUtils.refreshProgress(0, 0, nameMp + "下载成功", true);
                    if (DownloadList.getInstance().getCount() == 0 || mPosition >= DownloadList.getInstance().getCount()) {
                        stopService(new Intent(VersionUpdateService.this, MainActivity.class));
                    } else {
                        DownloadEvent downloadEvent = DownloadList.getInstance().getDownloadBeanList().get(mPosition - 1);
                        String name = downloadEvent.getName();
                        int iconId = downloadEvent.getIconId();
                        String downUrl = downloadEvent.getUrl();
                        if (downloadPath == null)
                            downloadPath = new DownloadPath(VersionUpdateService.this);
                        // 创建文件
                        File updateFile = downloadPath.getAllPath(name, downloadEvent.getType());
                        // 创建通知
                        createNotification(name, iconId);
                        try {
                            // 开始下载
                            downloadUpdateFile(downUrl, updateFile.getAbsolutePath(), name, iconId);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case DOWN_ERROR:
                    notificationUtils.refreshProgress(0, 0, nameMp + "下载失败", true);
                    if (DownloadList.getInstance().getCount() == 0 || mPosition >= DownloadList.getInstance().getCount()) {
//                        stopService(updateIntent);
                        stopService(new Intent(VersionUpdateService.this, MainActivity.class));
                    } else {
                        DownloadEvent downloadEvent = DownloadList.getInstance().getDownloadBeanList().get(mPosition - 1);
                        String name = downloadEvent.getName();
                        int iconId = downloadEvent.getIconId();
                        String downUrl = downloadEvent.getUrl();
                        if (downloadPath == null)
                            downloadPath = new DownloadPath(VersionUpdateService.this);
                        // 创建文件
                        File updateFile = downloadPath.getAllPath(name, downloadEvent.getType());
                        // 创建通知
                        createNotification(name, iconId);
                        try {
                            // 开始下载
                            downloadUpdateFile(downUrl, updateFile.getAbsolutePath(), name, iconId);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                default:
//                    stopService(updateIntent);
                    stopService(new Intent(VersionUpdateService.this, MainActivity.class));
                    break;
            }
        }
    };

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    /**
     * 启动下载服务
     *
     * @param context 上下文
     * @param cls     点击通知时跳转目标Activity
     */
    static DownloadEvent mDownloadEvent;

    public static void beginUpdate(Context context, Class<?> cls, DownloadEvent downloadEvent) {
        if (context == null) {
            throw new RuntimeException(
                    "Can't beginUpdate when the context is null!");
        }
        DownloadList.getInstance().addObject(downloadEvent);
        if (isStartServers)
            return;
        isStartServers = true;
        mDownloadEvent = downloadEvent;
        Intent updateIntent = new Intent(context, VersionUpdateService.class);
        mCls = cls;
        context.startService(updateIntent);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            mPosition = 0;
            String name = mDownloadEvent.getName();
            int iconId = mDownloadEvent.getIconId();
            String downUrl = mDownloadEvent.getUrl();
            if (downloadPath == null)
                downloadPath = new DownloadPath(this);
            // 创建文件
            File updateFile = downloadPath.getAllPath(name, mDownloadEvent.getType());
            // 创建通知
            createNotification(name, iconId);
            // 开始下载
            downloadUpdateFile(downUrl, updateFile.getAbsolutePath(), name, iconId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }


    /***
     * 创建通知栏
     */
    RemoteViews contentView;

    @SuppressWarnings("deprecation")
    public void createNotification(String appName, int iconId) {
        NotificationUtils notificationUtils = new NotificationUtils(VersionUpdateService.this, mPosition);
        notificationUtils.creatNotfication(appName, iconId);
        NotificationUtils.getNotificationUtilsList().put(mPosition, notificationUtils);
    }

    /***
     * 下载文件
     */
    public void downloadUpdateFile(String down_url, String file, final String appName, final int icont) throws Exception {
        updateFile = file;
        Log.i(TAG, ">>>>开始下载>>url>" + file);
        final OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder().url(down_url).build();
        final Call call = okHttpClient.newCall(request);
        isDownloadState = true;
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendMessage(appName, icont, DOWN_ERROR);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(updateFile);
                    long length = 0;
                    long timeMillis = System.currentTimeMillis();
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        length += len;
                        if (System.currentTimeMillis() - timeMillis > 1000) {//1秒刷新一次进度
                            refreshProgress(total, length, "", false);
                            timeMillis = System.currentTimeMillis();
                        }
                    }
                    fos.flush();
                    if (downloadStateEvent == null) downloadStateEvent = new DownloadStateEvent();
                    EventBus.getDefault().post(downloadStateEvent.setCurrent(100).setPosition(mPosition).setState(1));
                    // 下载成功
                    mPosition++;
                    sendMessage(appName, icont, DOWN_OK);
                } catch (final IOException e) {
                    if (downloadStateEvent == null) downloadStateEvent = new DownloadStateEvent();
                    EventBus.getDefault().post(downloadStateEvent.setCurrent(0).setPosition(mPosition).setState(-2));
                    mPosition++;
                    sendMessage(appName, icont, DOWN_ERROR);
                } finally {
                    try {
                        if (is != null) is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null) fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });

    }

    private void sendMessage(String name, int iconId, int state) {
        Message message = handler.obtainMessage();
        message.what = state;
        message.obj = name;
        message.arg1 = iconId;
        handler.sendMessage(message);
    }

    /**
     * 刷新进度条
     *
     * @param total
     * @param current
     */
    DownloadStateEvent downloadStateEvent;

    private void refreshProgress(long total, long current, String state, boolean isEnd) {
        NotificationUtils notificationUtils = NotificationUtils.getNotificationUtilsList().get(mPosition);
        notificationUtils.refreshProgress(total, current, state, isEnd);
        double x_double = current * 1.0;
        double tempresult = x_double / total;
        DecimalFormat df1 = new DecimalFormat("0.00"); // ##.00%
        // 百分比格式，后面不足2位的用0补齐
        String result = df1.format(tempresult);
        if (downloadStateEvent == null)
            downloadStateEvent = new DownloadStateEvent();
        EventBus.getDefault().post(downloadStateEvent.setCurrent((int) (Float.parseFloat(result) * 100)).setPosition(mPosition).setState(-1));
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        isDownloadState = false;
        mPosition = 0;
        mCls = null;
        DownloadList.getInstance().clearList();
        NotificationUtils.clearList();
        try {
            EventBus.getDefault().unregister(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理下载文件类型格式等的处理
     *
     * @param file
     * @return
     */
    public static Intent getFileIntent(File file) {
        Uri uri = Uri.fromFile(file);
        String type = getMIMEType(file);
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, type);
        return intent;
    }

    public static String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        // 取得扩展名
        String end = fName
                .substring(fName.lastIndexOf(".") + 1, fName.length());
        if (end.equals("apk")) {
            type = "application/vnd.android.package-archive";
        } else {
            // /*如果无法直接打开，就跳出软件列表给用户选择 */
            type = "*/*";
        }
        return type;
    }


}